﻿using Frame.Core.Auth;
using Frame.Core.Controllers;
using Frame.Core.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.DependencyInjection;
using System;

namespace Frame.Core.Attribute
{
    /// <summary>
    /// AppBoxMvc.Dapper自定义权限验证过滤器
    /// </summary>
    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
    public class CheckPowerAttribute : ActionFilterAttribute
    {
        /// <summary>
        /// 权限名称
        /// </summary>
        public string Name { get; set; }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            HttpContext context = filterContext.HttpContext;
            var permissionHandler = context.RequestServices.GetService<IPermissionHandler>();

            var isValid = permissionHandler.CheckPower(Name);
            // 权限验证不通过
            if (!String.IsNullOrEmpty(Name) && !isValid.Result)
            {
                if (context.Request.Method == "GET")
                {
                    BaseController.CheckPowerFailWithPage(context);
                    //http://stackoverflow.com/questions/9837180/how-to-skip-action-execution-from-an-actionfilter
                    // -修正越权访问页面时会报错[服务器无法在发送 HTTP 标头之后追加标头]（龙涛软件-9374）。
                    filterContext.Result = new EmptyResult();
                }
                else if (context.Request.Method == "POST")
                {
                    filterContext.Result = new JsonResult(new LayuiTableDataAjaxResult { codeIndex = 0, msg = "无权限" });
                }

            }
        }

    }
}
